package com.zhfj;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.ScrollableResults;

import java.util.List;

/**
 * Created on 2017/12/1.
 * 分页信息的封装
 *
 * @author Jie
 */
public class Page {
    /**
     * 结果集
     */
    private List result;
    /**
     * 一页的大小
     */
    private int pageSize;
    /**
     * 起始页 从1开始
     */
    private int startPage;

    private ScrollableResults scrollableResults;

    /**
     * 总记录的条数
     */
    private int totalResults;
    /**
     * 总页数
     */
    private int totalPages;
    /**
     * 是否为第一页
     */
    private boolean firstPage;
    /**
     * 是否为最后一页
     */
    private boolean lastPage;
    /**
     * 是否有上一页
     */
    private boolean hasPreviousPage;
    /**
     * 是否有下一页
     */
    private boolean hasNextPage;

    public Page(int startPage, int pageSize, Query query) {
        this.startPage = startPage;
        this.pageSize = pageSize;
        this.result = null;
        try {
            this.scrollableResults = query.scroll();
            this.scrollableResults.last();
            if (scrollableResults.getRowNumber() >= 0) {
                this.totalResults = this.scrollableResults.getRowNumber() + 1;
            } else {
                this.totalResults = 0;
            }
            //设置总页数
            setTotalPages();
            //根据分页条件来从query获取结果
            result = query.setFirstResult((this.getStartPage() - 1) * (this.getPageSize())).setMaxResults(this.getPageSize()).list();
        } catch (HibernateException e) {
            e.printStackTrace();
        }

    }

    public void setTotalPages() {
        this.totalPages = this.totalResults / this.pageSize;
        if (totalPages * pageSize < totalResults) {
            totalPages++;
        }
    }

    public List getResult() {
        return result;
    }

    public int getPageSize() {
        return pageSize;
    }

    public int getStartPage() {
        if (startPage < 1) {
            startPage = 1;
        }
        if (startPage > totalPages) {
            startPage = totalPages;
        }
        return startPage;
    }

    public ScrollableResults getScrollableResults() {
        return scrollableResults;
    }

    public int getTotalResults() {
        return totalResults;
    }

    public int getTotalPages() {
        return totalPages;
    }

    public boolean getFirstPage() {
        return this.startPage == 1;
    }

    public boolean getLastPage() {
        return this.startPage == totalPages;
    }

    public boolean getHasPreviousPage() {
        return this.startPage < totalPages;
    }

    public boolean getHasNextPage() {
        return this.startPage > 1;
    }
}
